package com.deuwise.config;

import io.swagger.annotations.ApiOperation;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.ApiKey;
import springfox.documentation.service.AuthorizationScope;
import springfox.documentation.service.SecurityReference;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.List;

import static com.google.common.collect.Lists.newArrayList;

/**
 * @author  chenwenchao
 * @date  2018-04-11
 * 设置不默认加载数据源
 */
@Configuration
@EnableSwagger2
public class Swagger2Configuration {

	@Bean
	public Docket createRestApi() {

		return new Docket(DocumentationType.SWAGGER_2)
				.groupName("系统内部接口")
				.apiInfo(apiInfo())
				.select()
				.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
				.apis(RequestHandlerSelectors.basePackage("com.deuwise.system"))
				.paths(PathSelectors.any())
				.build()
				.securitySchemes(securitySchemes())
				.securityContexts(securityContexts());
	}







	/**
	 * 设置Authorization认证头
	 * @return
	 */
	private List<ApiKey> securitySchemes() {
		return newArrayList(
				new ApiKey("Authorization", "Authorization", "header"));
	}
	/**
	 * global传header-Authorization值
	 * @return
	 */
	private List<SecurityContext> securityContexts() {
		return newArrayList(
				SecurityContext.builder()
						.securityReferences(defaultAuth())
						//.forPaths(PathSelectors.regex("^(?!auth).*$"))
						.build()
		);
	}


	List<SecurityReference> defaultAuth() {
		AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
		return newArrayList(
				new SecurityReference("Authorization", new AuthorizationScope[]{  authorizationScope}));
	}

	private ApiInfo apiInfo() {
		return new ApiInfoBuilder()
				.title("bootwV2.0")
				.version("2.0")
				.build();
	}

	/**
	 * 创建该API的基本信息（这些基本信息会展现在文档页面中）
	 * 访问地址：http://ip:port/swagger-ui.html
	 *
	 * @return
	 */
	private ApiInfo apiInfo(String title, String version) {
		return new ApiInfoBuilder()
				.title(title)
				.description("更多请关注: http://www.deuwise.com/")
				.version(version)
				.build();
	}

}